package com.example.demo.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.config.annotation.Token;
import com.example.demo.config.config.ErrorCode;
import com.example.demo.config.tool.MyJson;
import com.example.demo.config.config.WebException;
import com.example.demo.model.SysUser;
import com.example.demo.service.SysUserService;
import com.example.demo.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    TokenService tokenService;

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public Object find(@RequestParam("login_name") String userName, @RequestParam("login_pwd") String pwd, HttpServletRequest http) throws Exception {
        SysUser account = new SysUser();
        account.setLoginName(userName);
        account.setLoginPwd(pwd);

        Optional<SysUser> user = sysUserService.findOne(Example.of(account));
        if(!user.isPresent()){  //登录失败
            throw new WebException(ErrorCode.INCORRECT_USER_OR_PWD, "用户名或密码错误");
        }

        account = user.get();
        String token =  tokenService.getToken(account);
        JSONObject jsonObject = new JSONObject();


        jsonObject.put("token", token);
        JSONObject json = MyJson.toJsonObject(account);
        json.remove("login_pwd");
        jsonObject.put("user", json);

        return jsonObject;
    }

    @Token
    @RequestMapping(value = "account", method = RequestMethod.POST)
    public JSONObject account(HttpServletRequest http){
        String token = http.getHeader("token");
        Integer userId = tokenService.getUserId(token);
        JSONObject jsonObject = MyJson.toJsonObject(sysUserService.findById(userId));
        jsonObject.remove("login_pwd");
        return jsonObject;
    }
}

